/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable @typescript-eslint/no-use-before-define */
/* eslint-disable no-use-before-define */
// 获取实时出入库、新增站点、寄件订单数
import React, { useCallback, useState, useEffect, useMemo } from 'react';
import { connect } from 'dva';
import { useInterval, useUpdateEffect } from 'ahooks';
import { Row, Col } from 'antd';
import CountUp from '@/components/CountUp';
import CommonBorder from './Wrappers/CommonBorder';
import styles from './RealTimeArea.less';
import { changeScale } from './_utils';

const rateMap = {
  0: 0.98,
  1: 0.9,
  2: 0.85,
  3: 0.75,
  4: 0.7,
};

const Detail = connect(({ chartData, global }) => ({
  screenToken: global.screenToken,
  branchId: chartData.currentAreaInfo.branchId,
  currentLevel: chartData.currentAreaInfo.currentLevel,
}))(
  React.memo(({ title, subTitle, branchId, type, dispatch, screenToken, currentLevel }) => {
    const [data, setData] = useState({
      top: 0,
      sub: 0,
    });
    const [loading, setLoading] = useState(false);

    const rate = useMemo(() => rateMap[currentLevel] || 0.8, [currentLevel]);

    const fetchData = useCallback(
      () => {
        setLoading(true);
        dispatch({
          type: 'chartData/getRealTimeData',
          payload: {
            type,
            code: branchId,
            token: screenToken,
            level: currentLevel,
          },
        })
          .then(({ total, yz_total }) => {
            setData({
              top: total,
              sub: yz_total,
              cacheTag: `${branchId}_${type}`,
            });
            setLoading(false);
          })
          .catch(() => {
            setLoading(false);
          });
      },
      [branchId, dispatch, type, screenToken, currentLevel],
    );

    useUpdateEffect(fetchData, [fetchData]);

    useInterval(fetchData, 10 * 60 * 1000);

    useEffect(
      () => {
        // 字体自适应
        if (loading) {
          setTimeout(() => {
            const boxDom1 = document.getElementById(`boxDom_${type}_1`);
            const numDom1 = document.getElementById(`numDom_${type}_1`);
            const boxDom2 = document.getElementById(`boxDom_${type}_2`);
            const numDom2 = document.getElementById(`numDom_${type}_2`);
            const boxDom3 = document.getElementById(`boxDom_${type}_3`);
            const numDom3 = document.getElementById(`numDom_${type}_3`);
            changeScale(numDom1, boxDom1);
            changeScale(numDom2, boxDom2);
            changeScale(numDom3, boxDom3);
          }, 1500);
        }
      },
      [type, loading],
    );

    return (
      <CommonBorder showBg title={title} loading={loading}>
        <Row className={styles.content}>
          <Col id={`boxDom_${type}_1`}>
            <CountUp
              id={`numDom_${type}_1`}
              cacheInLocal
              duration={type == 'new_station' ? 0 : 11 * 60}
              ratio={type == 'new_station' ? 1 : rate}
              // branchId不能直接使用，会导致组件二次更新，影响缓存的准确性
              start={[data.top, data.cacheTag]}
            />
          </Col>
          <Col>
            <Row type="flex">
              <Col style={{ minWidth: 60 }}>{subTitle}：</Col>
              <Col id={`boxDom_${type}_2`} style={{ width: 'calc(100% - 60px)' }}>
                <span id={`numDom_${type}_2`}>
                  <CountUp
                    cacheInLocal
                    duration={type == 'new_station' ? 0 : 11 * 60}
                    ratio={type == 'new_station' ? 1 : rate}
                    // 缓存key不能重复
                    start={[data.sub, `${data.cacheTag}_sub`]}
                  />
                </span>
              </Col>
            </Row>
          </Col>
        </Row>
      </CommonBorder>
    );
  }),
);

const RealTimeArea = ({ type }) => (
  <CommonBorder title="实时数据">
    <Row type="flex" justify="space-between" gutter={[20, 0]}>
      <Col span={6}>
        <Detail type="in" title="入库数" subTitle="邮政" />
      </Col>
      <Col span={6}>
        <Detail type="out" title="出库数" subTitle="邮政" />
      </Col>
      <Col span={6}>
        <Detail type="new_station" title="新增站点" subTitle="累计" />
      </Col>
      <Col span={6}>
        <Detail
          type={type == 'gp' ? 'pda' : 'order_stat'}
          title={type == 'gp' ? '共配扫描数' : '寄件订单数'}
          subTitle="邮政"
        />
      </Col>
    </Row>
  </CommonBorder>
);

export default React.memo(RealTimeArea);
